package za.org.meraka.mxitstem.search;

import java.util.Properties;
import java.io.InputStream;
import java.io.File;
import java.io.FileReader;


import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.queryParser.QueryParser;
//import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;


import za.org.meraka.mxitstem.analysis.MxitAnalyzer;


public class Searcher {

Properties props;
IndexReader indexReader;
IndexSearcher indexSearcher;

private void searchIndex(String searchString) {
	try {
		Analyzer analyzer = new MxitAnalyzer();
		QueryParser queryParser = new QueryParser(Version.LUCENE_20, "contents", analyzer);
		Query query = queryParser.parse(searchString);
		System.out.println("searching for " + query.toString("contents"));
		indexSearcher.search(query, null, 100);
		System.out.println("searched");
		/*
		Hits hits = indexSearcher.search(query);
		System.out.println("there are " + hits.length() + " hits");
		int i;
		for(i=0 ; i<hits.length(); i++) {
			Document doc = hits.doc(i);

			System.out.println("contents " + doc.get("contents"));
		}
		*/
	}
	catch ( Throwable t ) {
		System.out.println("searchIndex throws " + t);
	}
}

public Searcher(String args[]) {
	System.out.println("searcher constructor");
	try {
		InputStream propStream = Searcher.class.getResourceAsStream("/mxitstem.properties");
		System.out.println("got property stream");
		props = new Properties();
		props.load(propStream);
		System.out.println("properties loaded");
		System.out.println("data.dir " + props.get("data.dir"));
		System.out.println("index.dir " + props.get("index.dir"));
		indexReader = IndexReader.open( FSDirectory.open(new File((String)props.get("index.dir"))), true); 
		indexSearcher = new IndexSearcher(indexReader);
		System.out.println("index opened");
		if ( args.length > 0 )
			searchIndex(args[0]);
		else
			System.out.println("nothing to search for");
	}
	catch ( Throwable t ) {
		System.out.println("Indexer constructor throwing " + t);
	}
}

public static void main(String args[]) {
	System.out.println("Searcher running");
	Searcher searcher = new Searcher(args);
}

}
